import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import './index.css'
import { Button, Drawer, Upload, message, Modal } from 'antd'
import React, { useEffect, useRef, useState } from 'react'
import { ColorContext } from '../wabjihe/dianjizh'
import { Popup,Cell  } from 'react-vant';

const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}
const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!')
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller that 2MB!');
    }
    return isJpgOrPng && isLt2M;
};

const Maheader = ({ color, setColor }) => {
     const [visible, setVisible] = useState(false)
    //颜色选择
    const [open, setOpen] = useState(false)
    const showDrawer = () => {
        setOpen(true)
    }
    const onClose = () => {
        setOpen(false)
    }
    let yans = [
        { color: 'red' },
        { color: '#871F78' },
        { color: '' },
        { color: '#ffffff' },
        { color: '#8E236B' },
        { color: '#D9D9F3' },
        { color: '#00FF00' },
        { color: '#6B238E' },
        { color: '#32CD99' },
        { color: '#5959AB' },
        { color: '#0000FF' },
        { color: '#2F4F4F' },
        { color: '#3232CD' },
        { color: '#6F4242' },
        { color: '#FF00FF' },
        { color: '#97694F' },
        { color: '#6B8E23' },
        { color: '#BC1717' },
        { color: '#00FFFF' },
        { color: '#7093DB' },
        { color: '#EAEAAE' },
        { color: '#238E68' },
        { color: '#FFFF00' },
        { color: '#855E42' },
        { color: '#9370DB' },
        { color: '#6B4226' },
        { color: '#000000' },
        { color: '#545454' },
        { color: '#426F42' },
        { color: '#8E6B23' },
        { color: '#70DB93' },
        { color: '#856363' },
        { color: '#7F00FF' }, { color: '#E6E8FA' },
        { color: '#5C3317' },
        { color: '#D19275' },
        { color: '#7FFF00' },
        { color: '#3299CC' },
        { color: '#9F5F9F' },
        { color: '#8E2323' },
        { color: '#70DBDB' },
        { color: '#007FFF' },
    ]
    //抠图
  const [selectedImage, setSelectedImage] = useState(null);
  const [processedImageData, setProcessedImageData] = useState(null);
  const canvasRef = useRef(null);
  const [clickedColor, setClickedColor] = useState('');

  const handleImageChange = (e) => {
    const file = e.target.files?.[0];
    if (file) {
      setSelectedImage(file);
    }
  };

  useEffect(() => {
    if (selectedImage && canvasRef.current) {
      const canvas = canvasRef.current;
      const ctx = canvas.getContext('2d');

      if (!ctx) {
        console.error('无法获取 2D 绘图上下文');
        return;
      }

        // 绘制原始图像到 canvas
      const image = new Image();
      image.src = URL.createObjectURL(selectedImage);
      image.onload = () => {
        canvas.width = image.width;
        canvas.height = image.height;
        ctx.drawImage(image, 0, 0);
      };
    }
  }, [selectedImage]);
  const handleCanvasClick = (e) => {
    if (canvasRef.current) {
      const canvas = canvasRef.current;
      const ctx = canvas.getContext('2d');

      if (!ctx) {
        console.error('无法获取 2D 绘图上下文');
        return;
      }

      const rect = canvas.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;

      const pixelData = ctx.getImageData(x, y, 1, 1).data;
      const color = `rgba(${pixelData[0]}, ${pixelData[1]}, ${pixelData[2]}, ${pixelData[3] / 255})`;
      setClickedColor(color);
    }
  };
  const simulateColorRemoval = () => {
    if (selectedImage && canvasRef.current && clickedColor) {
      const canvas = canvasRef.current;
      const ctx = canvas.getContext('2d');

      if (!ctx) {
        console.error('无法获取 2D 绘图上下文');
        return;
      }
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      const data = imageData.data;
      for (let i = 0; i < data.length; i += 4) {
        const currentColor = `rgba(${data[i]}, ${data[i + 1]}, ${data[i + 2]}, ${data[i + 3] / 255})`;
        if (currentColor === clickedColor) {
          data[i] = 0;
          data[i + 1] = 0;
          data[i + 2] = 0;
          data[i + 3] = 0;
        }
      }
      ctx.putImageData(imageData, 0, 0);
      const dataURL = canvas.toDataURL();
      setProcessedImageData(dataURL);
    }
  }
    const handleDownload = () => {
    if (processedImageData) {
      // 创建一个临时的a标签来触发下载
      const link = document.createElement('a');
      link.href = processedImageData;
      link.download = 'processed_image.png'; // 设置下载文件的名称
      link.click(); // 触发下载

      // 清理
      URL.revokeObjectURL(link.href); // 释放由createObjectURL创建的URL
      link.remove(); // 移除a标签
    }
  };

    return (
        <div>
            <Button type="primary" onClick={showDrawer}>颜色</Button>
            <Drawer title="选择颜色" onClose={onClose} open={open}>
                {
                    yans.map((item, index) => (
                        <button style={{ width: '45px', height: '45px', border: '1px solid #ccc', backgroundColor: item.color, borderRadius: '50%', margin: '5px', }} onClick={() => setColor(item.color)}></button>
                    ))
                }
            </Drawer>
            <span>调整位置</span>
            <Button  isLink onClick={() => setVisible(true)} >抠图</Button>
      <Popup visible={visible} onClose={() => setVisible(false)}>
                <div style={{ width: '800px', height: '450px' }}>
                    <div style={{width:'100%',height:'50px'}}><input type="file" onChange={handleImageChange} />
                        <button onClick={simulateColorRemoval}>删除点击颜色</button>
                    <button onClick={handleDownload} disabled={!processedImageData}>下载图片</button>
                    </div>
     <canvas style={{width:'100%',height:'380px'}} ref={canvasRef} onClick={handleCanvasClick} ></canvas>
     </div>
      </Popup>
          
        </div>
    )
}

export default Maheader